#include <stdio.h>
#include <string.h>

char * s_gets(char * st, int n);
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS  100     // 📚 书籍的最大数量

struct book {           // 建立book模板
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
};

void sort_by_input(const struct book library[], int n);
void sort_by_title(struct book library[], int n);
void sort_by_price(struct book library[], int n);

int main(void)
{
    struct book library[MAXBKS];
    int count = 0;
    int index;

    printf("Press [enter] at the start of a line to stop.\n");
    printf("请输入书籍的名称.\n");
    while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0')
    {
        printf("Now enter the author.\n");
        s_gets(library[count].author, MAXAUTL);
        printf("Now enter the value.\n");
        scanf("%f", &library[count++].value);
        while (getchar() != '\n')       // 清理输入行
            continue;
        if (count < MAXBKS)
            printf("Enter the next title.\n");
    }

    if (count > 0)
    {
        sort_by_input(library, count);
        sort_by_title(library, count);
        sort_by_price(library, count);
    } else
        printf("No books ? too bad.\n");

    return 0;
}

void sort_by_input(const struct book library[], int n)
{
    int i;

    printf("按照输入顺序打印：\n");
    for (i = 0; i < n; i++)
        printf("%s by %s: $%.2f\n", library[i].title, library[i].author, library[i].value);
    printf("\n");
}

void sort_by_title(struct book library[], int n)
{
    int i, j;
    struct book temp;
    // bubble sort
    for (i = 0; i < n-1; i++)
        for (j = 0; j < n-1-i; j++)
        {
            if (strcmp(library[j].title, library[j+1].title) > 0)
            {
                temp = library[j];
                library[j] = library[j+1];
                library[j+1] = temp;
            }
        }

    printf("按照书籍名称打印：\n");
    for (i = 0; i < n; i++)
        printf("%s by %s: $%.2f\n", library[i].title, library[i].author, library[i].value);
    printf("\n");
}

void sort_by_price(struct book library[], int n)
{
    int i, j;
    struct book temp;

    for (i = 0; i < n-1; i++)
        for (j = 0; j < n-1-i; j++)
            if (library[j].value > library[j+1].value)
            {
                temp = library[j];
                library[j] = library[j+1];
                library[j+1] = temp;
            }

    printf("按照书本价格升序打印：\n");
    for (i = 0; i < n; i++)
        printf("%s by %s: $%.2f\n", library[i].title, library[i].author, library[i].value);
    printf("\n");
}

char * s_gets(char * st, int n)
{
    char * ret_val;
    char * find;

    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        find = strchr(st, '\n');
        if (find)
            *find = '\0';
        else
            while (getchar() != '\n')
                continue;
    }

    return ret_val;
}